<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content login-content "
            :style="scale">
        <div class="login-body">
          <span class="angle angle-top"></span>
          <span class="angle angle-right"></span>
          <span class="angle angle-bottom"></span>
          <span class="angle angle-left"></span>
          <h3 class="login-title">完善企业信息</h3>
          <el-form :model="dataForm"
                   :rules="dataRule"
                   ref="dataForm"
                   @keyup.enter.native="dataFormSubmitHandle()"
                   status-icon>
            <el-form-item prop="customName">
              <el-input v-model.trim="dataForm.customName"
                        type="text"
                        :placeholder="$t('registered.customName')">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-home"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="address">
              <el-input v-model.trim="dataForm.address"
                        placeholder="请填写地址">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-location"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="realName">
              <el-input v-model.trim="dataForm.realName"
                        type="text"
                        placeholder="请填写联系人">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-user"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="mobile">
              <el-input v-model.trim="dataForm.mobile"
                        type="text"
                        placeholder="请填写联系电话">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-customerservice"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="email">
              <el-input v-model.trim="dataForm.email"
                        type="text"
                        placeholder="请填写邮箱地址">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-mail"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model.trim="dataForm.captcha"
                            :placeholder="$t('registered.code')">
                  </el-input>
                </el-col>
                <el-col :span="10"
                        class="login-captcha">
                  <el-button type="text"
                             @click="getCode">{{num>0 ? `${num}秒后重新获取`:'获取验证码' }}</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item prop="remark">
              <el-input v-model.trim="dataForm.remark"
                        type="text"
                        placeholder="请填写备注">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-mail"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="dataFormSubmitHandle()"
                         class="w-percent-100">{{ $t('registered.title') }}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success"
                         @click="goBack"
                         class="w-percent-100">返回上一步</el-button>
            </el-form-item>
          </el-form>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
// import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import { isEmail, isMobile } from '@/utils/validate'
// import * as CryptoJS from 'crypto-js'
import CryptoTool from '@/utils/cryptoTool'
export default {
  data () {
    let mobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (isMobile(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的手机号'))
        }
      }
    }
    let email = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        if (isEmail(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱'))
        }
      }
    }
    return {
      scale: {
        transform: `scale(1)`
      },
      timer: '',
      num: 0,
      i18nMessages: messages,
      captchaPath: '',
      str: '混淆字段',
      dataForm: {
        id: '',
        username: '',
        password: '',
        realName: '',
        email: '',
        mobile: '',
        duties: '',
        linkman: '',
        address: '',
        customName: '',
        captcha: '',
        remark: ''
      },
      dataRule: {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        confirm: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        customName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        mobile: [
          { required: true, validator: mobile, trigger: 'change' }
        ],
        captcha: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        realName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        email: [
          { required: true, validator: email, trigger: 'change' }
        ],
        duties: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        linkman: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        address: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        remark: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    let self = this
    let width = document.documentElement.offsetWidth
    let scaleNum = width * 0.0005208
    if (scaleNum > 1) {
      scaleNum = 1
    }
    self.scale = {
      transform: `scale(${scaleNum})`
    }

    let regist = window.sessionStorage.getItem('regist')
    if (regist) {
      regist = JSON.parse(CryptoTool.decrypt(regist))
      this.dataForm = {
        ...regist
      }
    }
    let pwd = this.$router.currentRoute.params.pwd
    let user = this.$router.currentRoute.params.user
    if (!pwd || !user) {
      let userInfo = sessionStorage.getItem('userInfo')
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        pwd = userInfo.pwd
        user = userInfo.user
      } else {
        pwd = ''
        user = ''
      }
    }
    this.dataForm.password = CryptoTool.decrypt(pwd)
    // this.dataForm.password = pwd
    this.dataForm.username = user
    let num = window.sessionStorage.getItem('num')
    if (!num) {
      return
    }
    num = CryptoTool.decrypt(num)
    num = num.replace(this.str, '')
    if (num > 0) {
      this.timer = setInterval(() => {
        let num = CryptoTool.decrypt(window.sessionStorage.getItem('num'))
        num = num.replace(this.str, '')
        num--
        this.num = num
        window.sessionStorage.setItem('num', CryptoTool.encrypt(num.toString() + this.str))
        if (num <= 0) {
          window.clearInterval(this.timer)
        }
      }, 1000)
    }
  },
  methods: {
    // 返回上一步
    goBack () {
      let data = this.dataForm
      data.captcha = ''
      window.sessionStorage.setItem('regist', CryptoTool.encrypt(JSON.stringify(data)))

      this.$router.push(
        {
          path: '/registered'
        })
    },
    getCode () {
      let time = window.sessionStorage.getItem('time')
      if (time) {
        time = CryptoTool.decrypt(time)
      }
      if (!isMobile(this.dataForm.mobile)) {
        this.$message.warning('请填写正确的手机号')
        return
      }
      let nowTime = new Date().getTime()
      if (nowTime - time > 60000) {
        let tempNum = 60
        window.sessionStorage.setItem('time', CryptoTool.encrypt(nowTime.toString()))
        window.sessionStorage.setItem('num', CryptoTool.encrypt(tempNum.toString()))
        // 获取短信
        this.$http.get(`/telcaptcha?phone=${this.dataForm.mobile}&scenarioType=${'registration'}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success('短信已发出，请注意接收')
        }).catch(() => { })
        // eslint-disable-next-line new-cap
        this.timer = setInterval(() => {
          let num = CryptoTool.decrypt(window.sessionStorage.getItem('num'))
          num = num.replace(this.str, '')
          num--
          this.num = num
          window.sessionStorage.setItem('num', CryptoTool.encrypt(num.toString() + this.str))
          if (num <= 0) {
            window.clearInterval(this.timer)
          }
        }, 1000)
      }
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          return false
        }
        if (!isEmail(this.dataForm.email)) {
          this.$message.warning('邮箱格式不正确')
          return false
        }

        if (this.dataForm.username === '' || this.dataForm.password === '') {
          this.$message.warning('请到注册页面填写用户名和密码')
          return
        }

        if (!this.dataForm.captcha.length) {
          this.$message.warning('请到填写验证码')
          // return
        }

        this.$http.post('/register', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            let data = this.dataForm
            data.captcha = ''
            window.sessionStorage.setItem('regist', CryptoTool.encrypt(JSON.stringify(data)))
            return this.$message.error(res.msg)
          }
          window.sessionStorage.removeItem('regist')
          window.sessionStorage.removeItem('userInfo')
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$router.replace({ name: 'login' })
            }
          })
        }).catch(() => {
          let data = this.dataForm
          data.captcha = ''
          window.sessionStorage.setItem('regist', CryptoTool.encrypt(JSON.stringify(data)))
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style lang="scss">
.login-header {
  img {
    width: 300px;
  }
}
.aui-page__login {
  .login-content {
    // padding: 0% 66% 150px !important;
  }
}
.login-title {
  color: wheat;
}
</style>
